Sieve Of Eratosthenes

94

Sieve Of Eratosthenes -

public static bool[] SieveOfEratosthenes(int num)
{
    bool[] isPrime = new bool[num + 1];
    for (int i = 2; i <= num; i++) isPrime[i] = true;
    // Removing multiples.
    for (int i = 2; i <= num; i++)
    {
        if (isPrime[i])
        {
            for (int j = i * 2; j <= num; j += i) 
            	isPrime[j] = false; // Eliminate multiples of i.                
        }
    }
    return isPrime;
}

sieve of eratosthenes -

function solution(n) {
   const numArr = new Array(n + 1);
   numArr.fill(true);
   numArr[0] = numArr[1] = false;
   for (let i = 2; i <= Math.sqrt(n); i++) {
      for (let j = 2; i * j <= n; j++) {
          numArr[i * j] = false;
      }
   }
   return numArr.filter(Boolean).length;
}

Sieve of Eratosthenes -

int n;
vector<bool> is_prime(n+1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i <= n; i++) {
    if (is_prime[i] && (long long)i * i <= n) {
        for (int j = i * i; j <= n; j += i)
            is_prime[j] = false;
    }
}

Comments

Submit
0 Comments